#include "BaseSaver.h"


bool BaseSaver::save(const char * fileName, HMM &hmm) {
	unsigned n = hmm.getNumberOfStates();
	unsigned m = hmm.getAlphabetSize();
	std::ofstream fout;
	fout.open(fileName, std::ios::out);
	if (!fout) {
		std::cout << "Unable to open save " << fileName << "\n";
		return false;
	} else {
		fout << m << " " << n;
		// write pi
		fout << "<pi>";
		for (size_t i = 0; i < n; i++) {
			fout << hmm.piAt(i) << " ";
		}
		fout << "\n</pi>\n";

		// write a
		fout << "<a>";
		for (size_t i = 0; i < n; i++) {
			for (size_t j = 0; j < n; j++) {
				fout << hmm.aAt(i, j) << " ";
			}
			fout << "\n";
		}
		fout << "</a>\n";

		// write b
		fout << "<b>";
		for (size_t i = 0; i < n; i++) {
			for (size_t j = 0; j < m; j++) {
				fout << hmm.bAt(i, j) << " ";
			}
			fout << "\n";
		}
		fout << "</b>\n";

		fout.close();
		return true;
	}
}

bool BaseSaver::addObservation(const char * fileName, Observation &obs) {
	std::ofstream fout;
	fout.open(fileName, std::ios::app);
	if (!fout) {
		std::cout << "Unable to open save " << fileName << "\n";
		return false;
	} else {
		fout << "obs " << obs.size() << "\n";
		for (size_t i = 0; i < obs.size(); i++) {
			fout << obs[i] << " ";
		}
		fout << "\n";
		fout.close();
		return true;
	}
}

bool BaseSaver::addTrack(const char * fileName, Track &t) {
	std::ofstream fout;
	fout.open(fileName, std::ios::app);
	if (!fout) {
		cout << "Unable to open save " << fileName << "\n";
		return false;
	} else {
		cout <<  "writing track to file " << fileName << "\n";
		fout <<  t.size() << "\n";
		for (size_t i = 0; i < t.size(); i++) {
			fout << t.getX(i) << " " << t.getY(i) << "\n";
		}
		fout.close();
		return true;
	}
}
